package sol.leetcode;

import def.TreeNode;

import java.util.ArrayList;
import java.util.List;

/**
 * Path Sum II
 */
public class Issue113 {
    public List<List<Integer>> pathSum(TreeNode root, int sum) {
        List<List<Integer>> res = new ArrayList<List<Integer>>();
        pathSum(root, sum, new ArrayList<Integer>(), res);
        return res;
    }

    private void pathSum(TreeNode root, int sum, List<Integer> prefix, List<List<Integer>> res) {
        if (root == null) return;

        List<Integer> newPrefix = new ArrayList<Integer>(prefix);
        newPrefix.add(root.val);

        if (root.left == null && root.right == null) {
            if (root.val == sum) {
                res.add(newPrefix);
            }
        } else {
            if (root.left != null)
                pathSum(root.left, sum - root.val, newPrefix, res);
            if (root.right != null)
                pathSum(root.right, sum - root.val, newPrefix, res);
        }
    }

    public static void main(String[] args) {
        TreeNode n1 = new TreeNode(5);
        TreeNode n2 = new TreeNode(4);
        TreeNode n3 = new TreeNode(8);
        TreeNode n4 = new TreeNode(11);
        TreeNode n5 = new TreeNode(13);
        TreeNode n6 = new TreeNode(4);
        TreeNode n7 = new TreeNode(7);
        TreeNode n8 = new TreeNode(2);
        TreeNode n9 = new TreeNode(5);
        TreeNode n10 = new TreeNode(1);
        n1.left = n2;
        n1.right = n3;
        n2.left = n4;
        n3.left = n5;
        n3.right = n6;
        n4.left = n7;
        n4.right = n8;
        n6.left = n9;
        n6.right = n10;

        Issue113 sol = new Issue113();
        List<List<Integer>> res = sol.pathSum(n1, 22);
        for (List<Integer> r : res)
            System.out.println(r);
    }
}
